package org.dei.perla.sys.dbutils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;

import org.dei.perla.sys.llqruntime.datastructures.Record;
import org.dei.perla.utils.PerlaRuntime;
import org.dei.perla.utils.logger.SimpleLogger;

public abstract class DBDumper {

	protected Connection conn;
	
	protected DBDumper(){
		
	}
	protected void initializeDB() {
		PerlaRuntime runtime = PerlaRuntime.getDefaultRuntime();
		String dbname = runtime.getProperty("PERLA_DB");
		String dbauth = runtime.getProperty("PERLA_DB_AUTH");

		if(dbname == null)
			dbname = "jdbc:mysql://localhost/perla?";

		if(dbauth == null)
			dbauth = "user=perla&password=perla";
		try {
			conn = DriverManager.getConnection(dbname + dbauth);
			initStatements();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void closeDB() {
		if (conn != null){
			try {
				SimpleLogger.log(this.getClass(), "Closing DB connection...");
				closeStatements();
				conn.close();
				SimpleLogger.log(this.getClass(), "...done");
			} catch(SQLException e) {
				SimpleLogger.log(this.getClass(), "Errore durante la chiusura della connessione al database");
			}
		}
	}
	
	protected abstract void closeStatements();
	protected abstract void initStatements();
	protected abstract void sendToDB(Record tRecord);

	public boolean process(ArrayList<Record> recordBlock){
		
		if(recordBlock == null)
			return false;
		if(recordBlock.size() == 0)
			return false;
		System.out.println( "process: start processing");
		this.initializeDB();
		for(Record record: recordBlock){
			sendToDB(record);
		}
		closeDB();
		System.out.println( "process stop processing");
		return true;
	}

	
}
